package controller

import (
	"errors"
	"web_app/models"

	"github.com/gin-gonic/gin"
)

const (
	ContextUserIdKey string = "userId"
)

var ErrorUserNotLogin = errors.New("用户未登录")
var ErrorPage = errors.New("传入的分页数据有误")

//GetCurrentUser 从上下文中获取当前登录的用户id
// GetCurrentUser 获取当前登录用户ID
// @Summary 获取当前登录用户ID
// @Description 获取当前登录用户ID
// @Tags 公共接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string true "Bearer 用户令牌"
// @Param object query userID  path    int     true        "_userID"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
func GetCurrentUser(c *gin.Context) (userId uint64, err error) {
	uid, ok := c.Get(ContextUserIdKey)
	if !ok {
		err = ErrorUserNotLogin
		return
	}
	userId, ok = uid.(uint64)
	if !ok {
		err = ErrorUserNotLogin
		return
	}
	return
}

// GetPageInfo 分页参数
// @Summary 分页参数
// @Description 分页参数
// @Tags 公共接口
// @Accept application/json
// @Produce application/json
// @Param Authorization header string true "Bearer 用户令牌"
// @Security ApiKeyAuth
// @Success 200 {object} _ResponsePostList
func GetPageInfo(c *gin.Context) (pagination models.Pagination, err error) {
	if err := c.ShouldBind(&pagination); err != nil {
		err = ErrorPage
		return pagination, err
	}

	if pagination.Limit < 0 {
		pagination.Limit = 2
	}
	if pagination.Page < 1 {
		pagination.Page = 1
	}
	if pagination.Sort != models.Time && pagination.Sort != models.Score {
		return
	}
	return
}
